﻿@namespace Masa.Tsc.Web.Admin.Rcl.Pages.App
@inherits ApmComponentBase
@page "/apm/app"

<div class="d-flex justify-space-between pt-2">
    <div class="d-flex">
        <SUserAutoComplete Small FillBackground=false Value="_userId" ValueChanged="UserChange" Class="@("user-auto-complete pr-2")" Placeholder="姓名/手机号码/Id" Label="姓名/手机号码/Id" Style="@("width:280px")" Clearable />

        <SAutoComplete Small Items="services" Value="@serviceName" ValueChanged="ServiceChange" Loading="isLoadService"
                       TItem="ValueTuple<string,string>"
                       TValue="string"
                       TItemValue="string"
                       ItemText="item=>item.Item1"
                       ItemValue="item=>item.Item1"
                       BackgroundColor="white"
                       Style="@("width:220px")"
                       Class="@("user-auto-complete pr-2")"
                       Placeholder="应用" Label="应用" Clearable>
            <ItemContent>
                <div class="d-flex justify-space-between m-list-item__title">
                    <div>@context.Item.Item1</div>
                    @if (!string.IsNullOrEmpty(context.Item.Item2))
                    {
                        <div style="color:#BDBDBD" class="pl-2">@context.Item.Item2</div>
                    }
                </div>
            </ItemContent>
        </SAutoComplete>

        <STextField Small Clearable Value="_searchText" ValueChanged="SearchValueChange" TValue="string" BackgroundColor="white" OnEnter="OnErrorChanged" Label="报错关键信息" Placeholder="报错关键信息" Style="@("width:280px")" Class="rounded-2" />
    </div>
    <div class="d-flex">
        <SDateTimeRangeToolbar Class="my-auto"
                               StartDateTime="@start.ToDateTimeOffset(CurrentTimeZone)"
                               EndDateTime="@end.ToDateTimeOffset(CurrentTimeZone)"
                               OnUpdate="OnTimeUpdate"
                               OnAutoUpdate="OnAutoTimeUpdate"
                               ShowQuickChange
                               ShowTimeZoneSelector
                               DefaultQuickRange="quickRangeKey"
                               ShowInterval />
    </div>
</div>
<div class="d-flex justify-space-between py-2">
    <div class="my-2 pl-1">APP版本号：@GetVersion(firstTrace?.Resource)</div>
    <div class="my-2 pl-4">终端类型：@ClientType()</div>
    <div class="my-2 pl-4">手机型号：@PhoneModel()</div>
    <div class="my-2 pl-4">操作系统：@ClientOs()</div>
    <div class="my-2 pl-4">Webview：@WebviewVersion()</div>
    <div class="my-2 pl-4 d-flex justify-start">
        <div>角色名称：</div><TooltipCopy TextFunc="(obj)=>RolesNames()" ValueFunc="(obj)=>RolesNames()" TextStyle="max-width:280px"> </TooltipCopy>
    </div>
    <div class="pl-4"><MButton OnClick="@(()=>claimShow=true)">查看用户申明数据</MButton></div>
</div>

<div class="d-flex flex-row">
    <!--left-->
    <div class="col-3 white rounded-lg py-0">
        <div class="py-4 d-flex">
            <SButton OnClick="Top" BorderRadiusClass="rounded-lg" Class="px-4">顶部</SButton>
            <SButton OnClick="Pre" BorderRadiusClass="rounded-lg" Class="ml-2 px-4"> 前一分钟</SButton>
            <MSwitch @bind-Value="showNormalClient" Label="显示正常Http" Class="my-2 py-0 pl-4"
                     Color="info"
                     HideDetails="true"></MSwitch>
        </div>
        @if (dataLoading)
        {
            <LoadingData DefaultClass="false" Style="@("height:calc(100vh - 378px)")" Class="full-width" />
        }
        else
        {
            <MVirtualScroll Height="@("calc(100vh - 378px)")" Items="data" Id="infinite-scroll-virtual" ItemSize="32">
                <ItemContent>
                    @((RenderFragment)(render => RenderTraces(render, context)))
                </ItemContent>
            </MVirtualScroll>
        }
        <div class="py-4">
            <SButton OnClick="Bottom" BorderRadiusClass="rounded-lg px-4">尾部</SButton>
            <SButton OnClick="Next" BorderRadiusClass="rounded-lg px-4" Class="ml-4"> 后一分钟</SButton>
        </div>
    </div>
    <!--end left-->
    <!--right-->
    <div class="col-9 py-0 pr-0">
        <div class="d-flex justify-space-between white rounded-t-xl">
            <div>
                <MTabs Value="index" Class="rounded-t-xl" ValueChanged="OnTabIndexChange">
                    <MTab Value="1">@I18n.Apm("Tabs.Metadata")</MTab>
                    <MTab Value="2">@I18n.Apm("Tabs.Trace")</MTab>
                    <MTab Value="3">@I18n.Apm("Tabs.Errors")</MTab>
                    <MTab Value="4">@I18n.Apm("Tabs.Logs")</MTab>
                    <MTab Value="5">@I18n.Apm("Tabs.Legend")</MTab>
                </MTabs>
            </div>
            <div><SIcon Class="pr-4 pt-2" Tooltip="分享" OnClick="Share">mdi-share</SIcon></div>
        </div>
        <CascadingValue Value="Search">
            <div style="height:calc(100vh - 288px)" class="overflow-y-scroll">
                <MTabsItems Value="index" Class="rounded-b-xl">
                    <MTabItem Value="1">
                        <ApmTraceView Value="@(currentLog!=null?currentLog.Data:currentTrace?.Data)" Dialog=false Height="@("calc(100vh - 400px)")" />
                    </MTabItem>
                    <MTabItem Value="2" Class="mx-2">
                        <Masa.Tsc.Web.Admin.Rcl.Pages.Apm.Endpoints.TimeLine Data="traceLines" IsMaui RoutePath="@(currentTrace!=null&&currentTrace.Data.Attributes.TryGetValue("http.target",out var target)?target.ToString():default)" Service="@serviceName" />
                    </MTabItem>
                    <MTabItem Value="3">
                        <Masa.Tsc.Web.Admin.Rcl.Pages.Apm.Services.ServiceErrors ShowChart=false />
                    </MTabItem>
                    <MTabItem Value="4">
                        <Masa.Tsc.Web.Admin.Rcl.Pages.Apm.Services.ServiceLogs ShowChart=false ShowAppEvent=false />
                    </MTabItem>
                    <MTabItem Value="5">
                        @if (!string.IsNullOrEmpty(_legend))
                        {
                            <MImage Src="@_legend" Class="mt-4 ml-8" Width="400" />
                        }
                        else
                        {
                            <div class="text-center h6 pt-4">请先到auth配置图例</div>
                        }
                    </MTabItem>
                </MTabsItems>
            </div>
        </CascadingValue>
    </div>
    <!--end right-->
</div>

<ApmTraceView Value="@claims" @bind-Show="claimShow" />
@code {
    private OperationLineTraceModel? currentTrace;
    private OperationLineLogModel? currentLog;
    private int treeIndex = 1;

    private readonly List<OperationLineTraceModel> data = new();

    public void UpdateData(List<TraceResponseDto> traces, List<LogResponseDto> logs)
    {

    }

    private async Task ChangeCurrent(OperationLineTraceModel trace, OperationLineLogModel? log = null)
    {
        currentTrace = trace;
        treeIndex = data.IndexOf(trace) + 1;
        currentLog = log;
        UpdateSearch();
        GetUrlLegend(trace);
        await LoadTraceTimeLines();
        StateHasChanged();
    }

    private void RenderTraces(RenderTreeBuilder __builder, OperationLineTraceModel item)
    {
        if (!showNormalClient && !(item.Data.Kind == "SPAN_KIND_SERVER" || item.Data.Kind == "Server") && !item.IsError)
            return;
        bool isSelected = currentLog == null && currentTrace != null && item == currentTrace;
        bool isSearchMatched = IsSearchKeyword(item);
        var color = item.IsError ? "red" : isSelected ? "yellow lighten-2" : isSearchMatched ? "orange lighten-2" : "light-green lighten-2";
        <div class="d-flex mt-1 text-caption @(isSelected?"grey pl-1":"")" @onclick="()=>ChangeCurrent(item)">
            <div class="pl-1 py-1 @color">@item.Time.UtcFormatLocal(CurrentTimeZone)</div>
            <div class="pl-4 pr-2 py-1 @color rounded-r-sm flex-grow-1">
                <MTooltip Top>
                    <ActivatorContent>
                        <div @attributes="@context.Attrs" class="text-truncate" style="width:210px">
                            @item.Text @item.Url
                        </div>
                    </ActivatorContent>
                    <ChildContent>
                        @item.Url
                    </ChildContent>
                </MTooltip>
            </div>
        </div>
        @((RenderFragment)(render => RenderLogs(render, item)))
    }

    private void RenderLogs(RenderTreeBuilder __builder, OperationLineTraceModel trace)
    {
        if (trace.Children == null || trace.Children.Count == 0)
            return;

        foreach (var item in trace.Children)
        {
            bool isSelected = currentLog != null && item == currentLog;
            bool isSearchMatched = IsSearchKeyword(item);
            var color = item.IsError ? "red" : isSelected ? "yellow lighten-2" : isSearchMatched ? "orange lighten-2" : "light-green lighten-2";
            <div class="d-flex mt-1 text-caption @(isSelected?"grey pl-1":"")" @onclick="()=>ChangeCurrent(trace,item)">
                <div class="pl-2 py-1 @color">@item.Time.UtcFormatLocal(CurrentTimeZone)</div>
                <div class="pl-5 py-1 @color"><MIcon Class="fa-solid fa-right-long" Small></MIcon></div>
                <div class="pl-2 py-1 pr-2 @color rounded-r-sm">点击</div>
                <div class="pr-4 py-1 @color rounded-r-sm flex-grow-1">@item.Text</div>
            </div>
        }
    }
}
